<template>
  <!-- 商品列表 -->
  <div id="proList">
    <crumbsbar
      :crumbs="crumbsBar"
      :searchWord="searchFilter.searchWord"
      @handlerSearch="handlerSearch">
      <template slot="other">
        <el-button class="bg-btn el-icon-plus" @click="handleAddData">添加商品</el-button>
      </template>
    </crumbsbar>

    <el-row type="flex">
      <el-col :span="16">
        <div class="style-select">
          <el-row type="flex">
            <el-col :span="4">
              <!-- 这个getData 如果加 () ，会把当前 v-model 里的值当作参数传过去，会造成bug -->
              <el-select @change="getData()" v-model="searchFilter.typeId" placeholder="请选择产品类型">
                <el-option label="产品类型" value></el-option>
                <el-option
                  v-for="item in searchFilter.typeIdArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-select @change="getData()" v-model="searchFilter.cateId" placeholder="请选择产品分类">
                <el-option label="产品分类" value></el-option>
                <el-option
                  v-for="item in searchFilter.cateIdArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-select @change="getData()" v-model="searchFilter.acpId" placeholder="请选择厂商">
                <el-option label="厂商" value></el-option>
                <el-option
                  v-for="item in searchFilter.acpIdArr"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-select @change="getData()" v-model="searchFilter.rechargeMode" placeholder="请选择到账方式">
                <el-option label="到账方式" value></el-option>
                <el-option label="直充" value="0"></el-option>
                <el-option label="卡密" value="1"></el-option>
              </el-select>
            </el-col>
            <el-col :span="4" :offset="1">
              <el-select @change="getData()" v-model="searchFilter.status" placeholder="请选择状态">
                <el-option label="状态" value></el-option>
                <el-option label="启用" value="1"></el-option>
                <el-option label="停用" value="0"></el-option>
              </el-select>
            </el-col>
          </el-row>
        </div>

      </el-col>

      <el-col :span="7" :offset="1">
        <el-row type="flex" justify="end">
          <!--<el-col :span="5" class="t-a-r mr10">-->
          <!--</el-col>-->
          <el-button
            class="text-btn"
            :class="{'text-btn-active':multipleSelection.length>0}"
            :disabled="multipleSelection.length===0"
            @click="handleEnableData(1)"
             style="width:100%;"
          >批量启用
          </el-button>
          <el-button
            class="text-btn"
            :class="{'text-btn-active':multipleSelection.length>0}"
            :disabled="multipleSelection.length===0"
            @click="handleEnableData(0)"
             style="width:100%;"
          >批量停用
          </el-button>
          <el-button
            class="text-btn"
            :class="{'text-btn-active':multipleSelection.length>0}"
            :disabled="multipleSelection.length===0"
            @click="handleDelData()"
             style="width:100%;"
          >批量删除
          </el-button>
        </el-row>
      </el-col>
    </el-row>

    <div class="container">
      <div class="table-box">
        <el-table
          :data="tableData"
          ref="multipleTable"
          border
          stripe
          highlight-current-row
          @row-click="toggleClicked"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="aiCode" label="商品编号" align="center" width="80"></el-table-column>
          <el-table-column prop="atName" label="产品类型" align="center"></el-table-column>
          <el-table-column prop="aiName" label="商品名称" align="center">
            <template slot-scope="scope">
              <p class="text-filter-2" :title="scope.row.aiName">{{scope.row.aiName}}</p>
            </template>
          </el-table-column>
          <el-table-column prop="acName" label="产品分类" align="center"></el-table-column>
          <el-table-column label="商品图标" align="center">
            <template slot-scope="scope">
              <img
                v-if="scope.row.aiIcon"
                class="g-icon"
                :src="(scope.row.aiIcon?ftpUrl+scope.row.aiIcon:'')"
                width="40"
                height="40"
                :onerror="baseUploadImg"
              >
              <span v-else>暂无图标</span>
            </template>
          </el-table-column>
          <el-table-column prop="acpName" label="厂商" align="center"></el-table-column>
          <el-table-column prop="modifyTime" label="修改时间" align="center">
            <template slot-scope="scope">
              <span v-html="formatDate(scope.row.modifyTime, 'yyyy-MM-dd hh:mm:ss')"></span>
            </template>
          </el-table-column>
          <el-table-column prop="aiRechargeMode" label="到账方式" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.aiRechargeMode==0?'直充':'卡密'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="aiStatus" label="状态" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.aiStatus==0?'停用':'启用'}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="id" label="操作" align="center" width="220">
            <template slot-scope="scope">
              <el-button
                class="btn-sm row-btn font-c"
                v-if="scope.row.aiStatus!=2"
                size="small"
                @click="toggleSelection(); multipleSelection.push(scope.row); handleEnableData(scope.row.aiStatus==0?1:0)"
              >{{scope.row.aiStatus==1?'停用':'启用'}}
              </el-button>
              <el-button
                class="btn-sm row-btn font-c"
                v-if="scope.row.aiStatus!=2"
                size="small"
                @click="handleEditData(scope.row)"
              >编辑
              </el-button>
              <el-button
                class="btn-sm row-btn font-c"
                v-if="scope.row.aiStatus!=2"
                size="small"
                @click="toggleSelection(); multipleSelection.push(scope.row); handleDelData()"
              >删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <page
        :orderList="tableData"
        :totalCount="totalCount"
        :page="page"
        :limit="10"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
        class="page"
      ></page>
    </div>
  </div>
</template>
<script>
  export default {
    name: "list",
    data() {
      return {
        baseUrl: this.$baseUrl,
        ftpUrl: this.$ftpUrl,
        baseUploadImg:'this.src="' + this.$baseUploadImg + '"',
        downloadImg: this.$api.downFile,
        /** 头部部分 **/
        crumbsBar: {
          name: "商品列表",
          placeholder: "检索商品编号、商品名称",
          span: [7, 2]
        },

        /** 列表部分 **/
        totalCount: 0, //数据总数
        page: 1, //当前页码
        tableData: [],
        multipleSelection: [],

        /** 检索条件 **/
        searchFilter: {
          searchWord: "",

          typeIdArr: [],
          cateIdArr: [],
          acpIdArr: [],
          acctIdArr: [],
          gameIdArr: [],

          typeId: "",
          cateId: "",
          acpId: "",
          rechargeMode: "",
          status: ""
        }
      };
    },
    created() {
      this.getSelectArr();
      this.getData();
    },
    mounted() {
    },
    computed: {},
    methods: {
      // 搜索按钮
      handlerSearch(v) {
        this.searchFilter.searchWord = v;
        this.page = 1;
        this.getData();
      },
      // 获取数据
      getData(p, s) {
        let page = p ? p : 1;
        let size = s ? s : 10;

        let searchData = {
          page: page,
          limit: size,
          query: this.searchFilter.searchWord,
          cateId: this.searchFilter.cateId,
          typeId: this.searchFilter.typeId,
          acpId: this.searchFilter.acpId,
          rechargeMode: this.searchFilter.rechargeMode,
          status: this.searchFilter.status
        };
        this.$postFetch(this.$api.ProList, searchData)
          .then(response => {
            let res = response.data;
            if (res.code !== 1) {
              console.log(res);
              this.$message.error(res.msg);
              return;
            }

            this.totalCount = res.data.totalCount;
            this.tableData = res.data.rows;
          })
          .catch(err => {
            console.log(err);
          });
      },
      // 每页条数切换
      handleSizeChange(v) {
        this.limit = v;
        this.getData(this.page, this.limit);
      },
      // 分页导航
      handleCurrentChange(val) {
        this.page = val;
        this.getData(this.page, this.limit);
      },
      // 选中商品
      handleSelectionChange(val) {
        // console.log(val); // 根据观察，传来的值是个数组，所以直接赋值
        this.multipleSelection = val;
      },
      // 行点击事件
      toggleClicked(row){
        this.$refs.multipleTable.toggleRowSelection(row);
      },
      // 取消选中
      toggleSelection(rows) {
        if (rows) {
          // 取消指定行
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row);
          });
        } else {
          // 取消所有行
          this.$refs.multipleTable.clearSelection();
        }
      },
      // 获取添加商品中select的数据
      getSelectArr() {
        // // 帐号类型(列表不用)
        // this.$postFetch(this.$api.actList).then(response => {
        //   if (response.data.code !== 1) { this.$message.error(response.data.msg); return; }
        //   this.searchFilter.acctIdArr = response.data.data;
        // }).catch(err => { console.log(err); });
        //
        // // 区服配置(列表不用)
        // this.$postFetch(this.$api.gameList).then(response => {
        //   if (response.data.code !== 1) { this.$message.error(response.data.msg); return; }
        //   this.searchFilter.gameIdArr = response.data.data;
        // }).catch(err => { console.log(err); });

        // 分类
        this.$postFetch(this.$api.appcateList)
          .then(response => {
            if (response.data.code !== 1) {
              this.$message.error(response.data.msg);
              return;
            }
            this.searchFilter.cateIdArr = response.data.data;
          })
          .catch(err => {
            console.log(err);
          });

        // 产品类型
        this.$postFetch(this.$api.apptypeList)
          .then(response => {
            if (response.data.code !== 1) {
              this.$message.error(response.data.msg);
              return;
            }
            this.searchFilter.typeIdArr = response.data.data;
          })
          .catch(err => {
            console.log(err);
          });

        // 厂商
        this.$postFetch(this.$api.companyList)
          .then(response => {
            if (response.data.code !== 1) {
              this.$message.error(response.data.msg);
              return;
            }
            this.searchFilter.acpIdArr = response.data.data;
          })
          .catch(err => {
            console.log(err);
          });
      },

      handleAddData() {
        this.$router.push({path: "/product/detail", query: {id: ""}});
      },
      handleEditData(val) {
        this.$router.push({path: "/product/detail", query: {id: val.aiId}});
      },
      //删除/批量删除
      handleDelData() {
        if (this.multipleSelection.length === 0) {
          this.$message.error("请选择要删除的商品");
          return;
        }
        let  ai_name = "";
        this.multipleSelection.forEach(key=>{
          ai_name = key.aiName
          console.log(ai_name);
        })
        let options = {};
        if (this.multipleSelection.length === 1) {
          options = {
            title: "删除商品",
            content: `<div>是否确认删除${ai_name}?</div><div style="margin-top:10px;">删除后所有商户中该商品删除！</div>`,
          }
        } else {
          options = {
            title: "批量删除",
            content: `<div>是否确认删除选中的共${this.multipleSelection.length}项商品?</div><div style="margin-top:10px;">删除后所有商户中该商品删除！</div>`,
          }
        }

        // let options = {
        //   title: (this.multipleSelection.length === 1)?'删除商品':'批量删除',
        //   content: `<div>是否确认删除选中的共${this.multipleSelection.length}项商品?</div><div style="margin-top:10px;">删除后所有商户中该商品删除！</div>`,
        // };
        console.log(this.multipleSelection);
        this.$myconfirm("删除商品", options)
          .then(() => {
            let ids = [];
            for (let i = 0; i < this.multipleSelection.length; i++) {
              if (this.multipleSelection[i].aiStatus !== 0) {
                this.$message.error("商品停用后才可以删除");
                return;
              }
              ids.push(this.multipleSelection[i].aiId);
            }

            let postData = {aiIds: ids};
            this.$postFetch(this.$api.ProDelete, postData)
              .then(response => {
                if (response.data.code !== 1) {
                  this.$message.error(response.data.msg);
                  return;
                }
                this.$message.success('成功');
                this.getData();
              })
              .catch(err => {
                console.log(err);
              });
            this.multipleSelection = [];
            this.toggleSelection();
          })
          .catch(() => {
            this.multipleSelection = [];
            this.toggleSelection();
          });
      },
      //启用/停用
      handleEnableData(state) {
        let messageTips = "启用";
        if (state == 0) {
          messageTips = "停用";
        }
        if (this.multipleSelection.length === 0) {
          this.$message.error("请选择要" + messageTips + "的商品");
          return;
        }
        let  ai_name = "";
        let count_up = [];   //所有启用状态
        let count_down = []; //所有停用状态
        console.log(this.multipleSelection);
        this.multipleSelection.forEach(key=>{
          ai_name = key.aiName;
          if (key.aiStatus==1) {
            count_up.push(key.aiStatus)
          }else {
            count_down.push(key.aiStatus)
          }
          // console.log(ai_name);
          // console.log(count_up.length);
          // console.log(count_down.length);
        })
        let options = {};
        if (this.multipleSelection.length === 1) {
          options = {
            title: messageTips,
            content: `<div>是否确认`+messageTips+`${ai_name}?</div><div style="margin-top:10px;">`+messageTips+`后所有商户中该商品`+messageTips+`！</div>`,
          }
        } else {
          options = {
            title: "批量" + messageTips,
            content:`<div>是否确认`+messageTips+`选中的共${state == 0?count_up.length:count_down.length}项商品?</div><div style="margin-top:10px;">`+messageTips+`后所有商户中该商品`+messageTips+`！</div>`,
          }
        }

        // let options = {
        //   title: messageTips + "商品",
        //   content:
        //     `<div>是否确认` +
        //     messageTips +
        //     `选中的共${
        //       this.multipleSelection.length
        //       }项商品?</div><div style="margin-top:10px;">` +
        //     messageTips +
        //     `后所有商户中该商品` +
        //     messageTips +
        //     `！</div>`
        // };
        this.$myconfirm(messageTips + "商品", options)
          .then(() => {
            console.log(this.multipleSelection);
            let ids = [];
            this.multipleSelection.forEach(key => {
              if(state !== key.aiStatus){
                ids.push(key.aiId);
              }
            });
            let postData = {status: state, aiIds: ids};
            this.$postFetch(this.$api.ProEnable, postData)
              .then(response => {
                if (response.data.code !== 1) {
                  this.$message.error(response.data.msg);
                  return;
                }
                this.$message.success('成功');
                this.multipleSelection = [];
                this.getData();
              })
              .catch(err => {
                console.log(err);
              });
            this.multipleSelection = [];
            this.toggleSelection();
          })
          .catch(() => {
            this.multipleSelection = [];
            this.toggleSelection();
          });
      },
      formatDate(value, format) {
        return new Date(value)
          .Format(format)
          .toString()
          .replace(" ", "<br/>");
      }
    },
    components: {}
  };
</script>
<style>
  .row-btn {
    border: 1px solid #7d72e4;
  }

  .row-btn + .row-btn {
    margin-left: 5px;
  }
</style>
